package cn.gx.kevin.controller;

import cn.gx.kevin.common.ui.AdminControllerHelper;
import com.alibaba.fastjson.JSONArray;
import cn.gx.kevin.common.annotation.ApiDescript;
import cn.gx.kevin.common.annotation.ApiParams;
import cn.gx.kevin.common.annotation.ApiParamsDesc;
import cn.gx.kevin.common.annotation.ApiReturnDesc;
import cn.gx.kevin.common.emun.XlsCellDataTypeEnum;
import cn.gx.kevin.common.ui.AjaxResult;
import cn.gx.kevin.common.utils.DateUtils;
import cn.gx.kevin.domain.Func;
import cn.gx.kevin.domain.Menu;
import cn.gx.kevin.service.IFuncService;
import cn.gx.kevin.service.IMenuService;
import cn.gx.kevin.controller.ResetfulBaseController;
import cn.gx.kevin.service.IBaseService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.*;

/**
 * Generate by Kevin's CodeBuilder
 **/
@ApiDescript("系统功能管理模块(系统会扫描datagrid里面配置的按钮权限码，形成权限数据)")
@Controller
@RequestMapping(value = "/func")
public class FuncController extends ResetfulBaseController<Func, String>  {

    IFuncService funcService;

    @Resource(name = "menuService")
    IMenuService menuService;

    @Resource(name = "funcService")
    @Override
    public void setService(IBaseService<Func, String> service) {
        this.service = service;
        funcService = (IFuncService)service;
    }

    @Override
    @RequestMapping(value = "/page/{pageName}", method = RequestMethod.GET)
    public String page(@PathVariable("pageName") String pageName, HttpServletRequest request) throws Exception {
        return super.page(pageName, request);
    }

    @Override
    protected void onRequestPage(String pageName, HttpServletRequest request) throws Exception {
        if ("index".equals(pageName) || "form".equals(pageName)) {
            JSONArray menuJson = menuService.getMenuJsonByPid("0");
            request.setAttribute("menuJson", menuJson);
        }
    }

    /*
     * 页面 views/base/entityPath 文件夹路径
     * ***/
    @Override
    public String setPageModelPath(HttpServletRequest request) {
        // TODO Auto-generated method stub
        return "base" + File.separator + entityPath;
    }

    @Override
    @ApiDescript("新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult add(HttpServletRequest request) throws Exception {
        return super.add(request);
    }

    @Override
    @ApiDescript("更新")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public @ResponseBody AjaxResult update(HttpServletRequest request) throws Exception {
        return super.update(request);
    }

    @Override
    @ApiDescript("删除")
    @ApiParams("{'idList':'id1,id2'}")
    @RequestMapping(value = "/delete")
    public @ResponseBody AjaxResult delete(HttpServletRequest request) throws Exception {
        return super.delete(request);
    }

    @Override
    @ApiDescript("分页多条件可排序查询")
    @ApiParams("{'page':1,'pageSize':15,'_col_sort_fieldName':'asc'}")
    @ApiParamsDesc("{page:'当前页',pageSize:'页大小',_col_sort_fieldName:'desc/asc，_col_sort_为前缀标志，fieldName为需要排序的字段名'}")
    @RequestMapping(value = "/list")
    public @ResponseBody AjaxResult list(HttpServletRequest request) throws Exception {
        return super.list(request);
    }


    @ApiDescript("导出xls")
    @ApiParams("{}")
    @RequestMapping("export")
    public void exportXls(HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.setDownLoadFlag(request);
        String fileName = DateUtils.formatCurrentDateTime("yyyyMMddHHmmss")+ "功能列表.xlsx";
        String file = this.createDir("tmp",request)  + fileName;
        File tmpFile = new File(file);
        OutputStream fileOutputStream = null;
        try{
            tmpFile.createNewFile();
            fileOutputStream = new FileOutputStream(tmpFile);
            this.funcService.export(fileOutputStream);
            FileInputStream inputStream = new FileInputStream(tmpFile);
            AdminControllerHelper.responseFile(response,"功能列表.xlsx","application/msexcel",inputStream);
            this.clearDownLoadFlag(request);
        }catch (Exception x){
            logger.error("{}",x);
            AdminControllerHelper.responseJson(response,1,"导出失败！",null);
        }finally {
            if(fileOutputStream != null){
                try{
                    fileOutputStream.close();
                }catch (Exception x){}
            }
            FileUtils.deleteQuietly(tmpFile);
        }
    }


    @ApiDescript("导入xls")
    @ApiParams("{}")
    @RequestMapping("import")
    public @ResponseBody AjaxResult importOrg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile xlsFile = fileMap.get("attachments");
        long count =  this.funcService.importFuncs(xlsFile);
        return returnSuccMsg("成功导入："+count);
    }




    @Override
    protected Map<String, Object> setListParams(HttpServletRequest request) throws Exception {
        Map<String, Object> prs = new HashMap<String, Object>();
        String menuId = request.getParameter("menuId");
        if (StringUtils.isNotEmpty(menuId)) {
            prs.put("menuId", menuId);
        }
        return prs;
    }


    @ApiReturnDesc("{ code: '0正确/1异常',message: '信息',data: '数据对象'}")
    @ApiParamsDesc("{id:'id'}")
    @ApiDescript("根据ID查询数据")
    @ApiParams("{'id':''}")
    @Override
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public @ResponseBody AjaxResult get(String id) throws Exception {
        return super.get(id);
    }

}
